package com.anyi.gulimall.ware.service.impl;

import com.anyi.gulimall.common.contants.ProductConstant;
import com.anyi.gulimall.common.contants.WareConstant;
import com.anyi.gulimall.common.utils.R;
import com.anyi.gulimall.ware.dao.WmsWareSkuDao;
import com.anyi.gulimall.ware.entity.WmsPurchaseDetailEntity;
import com.anyi.gulimall.ware.entity.WmsWareSkuEntity;
import com.anyi.gulimall.ware.feign.ProductFeignService;
import com.anyi.gulimall.ware.service.WmsPurchaseDetailService;
import com.anyi.gulimall.ware.service.WmsWareSkuService;
import com.anyi.gulimall.ware.vo.PurchaseDoneItemVo;
import com.anyi.gulimall.ware.vo.PurchaseDoneVo;
import com.anyi.gulimall.ware.vo.PurchaseMergeVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.anyi.gulimall.common.utils.PageUtils;
import com.anyi.gulimall.common.utils.Query;

import com.anyi.gulimall.ware.dao.WmsPurchaseDao;
import com.anyi.gulimall.ware.entity.WmsPurchaseEntity;
import com.anyi.gulimall.ware.service.WmsPurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wmsPurchaseService")
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseDao, WmsPurchaseEntity> implements WmsPurchaseService {

    @Autowired
    private WmsPurchaseDetailService wmsPurchaseDetailService;

    @Autowired
    private WmsWareSkuDao wmsWareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<WmsPurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的需求单
     * @return
     */
    @Override
    public PageUtils getUnReceive(Map<String, Object> params) {
        LambdaQueryWrapper<WmsPurchaseEntity> wrapper = new LambdaQueryWrapper<WmsPurchaseEntity>()
                .eq(WmsPurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .or().eq(WmsPurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());

        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 将需求项合并成需求单
     * @param purchaseMergeVo
     */
    @Transactional
    @Override
    public void merge(PurchaseMergeVo purchaseMergeVo) {
        // 判断该购物单是否存在
        Long purchaseId = purchaseMergeVo.getPurchaseId();
        if (StringUtils.isEmpty(purchaseId)){
            WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
            wmsPurchaseEntity.setCreateTime(new Date());
            wmsPurchaseEntity.setUpdateTime(new Date());
            this.save(wmsPurchaseEntity);
            purchaseId = wmsPurchaseEntity.getId();
        }
        // 修改当前所有项的id
        List<Long> items = purchaseMergeVo.getItems();
        for (Long item : items) {
            WmsPurchaseDetailEntity wmsPurchaseDetail = wmsPurchaseDetailService.getById(item);
            wmsPurchaseDetail.setPurchaseId(purchaseId);
            wmsPurchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            wmsPurchaseDetailService.updateById(wmsPurchaseDetail);
        }
    }
    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 根据id 修改 需求单的状态
        List<WmsPurchaseEntity> collect = ids.stream().map(id -> {
            WmsPurchaseEntity byId = this.getById(id);
            byId.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            // 修改需求项的状态信息
            List<WmsPurchaseDetailEntity> list = wmsPurchaseDetailService.list(new LambdaQueryWrapper<WmsPurchaseDetailEntity>().eq(WmsPurchaseDetailEntity::getPurchaseId, id));
            List<WmsPurchaseDetailEntity> wmsPurchaseDetailEntities = list.stream().map(item -> {
                item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return item;
            }).collect(Collectors.toList());
            wmsPurchaseDetailService.updateBatchById(wmsPurchaseDetailEntities);
            return byId;
        }).collect(Collectors.toList());
        this.updateBatchById(collect);
    }

    /**
     * 完成需求单
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        // 是否所有需求项已经完成，修改状态
        Long id = purchaseDoneVo.getId();
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        Boolean flag = true;

        for (PurchaseDoneItemVo item : items) {
            WmsPurchaseDetailEntity wmsPurchaseDetailEntity = wmsPurchaseDetailService.getById(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag =false;
            }
            // 设置需求项状态
            wmsPurchaseDetailEntity.setStatus(item.getStatus());
            // 修改库存信息
            List<WmsWareSkuEntity> list = wmsWareSkuDao.selectList(new LambdaQueryWrapper<WmsWareSkuEntity>().eq(WmsWareSkuEntity::getSkuId, wmsPurchaseDetailEntity.getSkuId()));
            if (list !=null && list.size() !=0){
                wmsWareSkuDao.updateStock(wmsPurchaseDetailEntity.getSkuId(),wmsPurchaseDetailEntity.getWareId(),wmsPurchaseDetailEntity.getSkuNum());
            }else{
                WmsWareSkuEntity wmsWareSkuEntity = new WmsWareSkuEntity();
                wmsWareSkuEntity.setSkuId(wmsPurchaseDetailEntity.getSkuId());
                wmsWareSkuEntity.setWareId(wmsPurchaseDetailEntity.getWareId());
                wmsWareSkuEntity.setStock(wmsPurchaseDetailEntity.getSkuNum());
                wmsWareSkuEntity.setStockLocked(0);
                // 查询商品的名字
                R info = productFeignService.info(wmsPurchaseDetailEntity.getSkuId());
                if (info.getCode() ==0){
                    Map<String ,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                    String  skuName = (String) skuInfo.get("skuName");
                    wmsWareSkuEntity.setSkuName(skuName);
                }
                wmsWareSkuDao.insert(wmsWareSkuEntity);
            }
            wmsPurchaseDetailService.updateById(wmsPurchaseDetailEntity);
        }

        // 修改需求单的状态
        WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
        wmsPurchaseEntity.setId(id);
        wmsPurchaseEntity.setUpdateTime(new Date());
        wmsPurchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(wmsPurchaseEntity);


    }

}